import './lib/wxPromise.min.js'
import regeneratorRuntime from './lib/wxPromise.min.js'
import uuidv1 from './lib/uuid/uuid.modified'
import * as API_Connect from './api/connect'
import * as API_Common from './api/common'
import * as API_Member from './api/members'
import * as API_Trade from './api/trade'
// 小程序自动登录
App({
  onLaunch() {

    const updateManager = wx.getUpdateManager()

    updateManager.onCheckForUpdate(function (res) {
      // 请求完新版本信息的回调
      console.log(res.hasUpdate)
    })

    updateManager.onUpdateReady(function () {
      wx.showModal({
        title: '更新提示',
        content: '新版本已经准备好，是否重启应用？',
        success(res) {
          if (res.confirm) {
            // 新的版本已经下载好，调用 applyUpdate 应用新版本并重启
            updateManager.applyUpdate()
          }
        }
      })
    })

    updateManager.onUpdateFailed(function () {
      // 新版本下载失败
    })
    // 生成uuid
    if (!wx.getStorageSync('uuid')) {
      wx.setStorageSync('uuid', uuidv1.v1())
      this.globalData.uuid = wx.getStorageSync('uuid')
    }
    // 获取站点信息
    API_Common.getSiteData().then(response => {
      this.globalData.site_name = response.site_name
    })
    // 授权检测
    // if (!wx.getStorageSync('refresh_token')) {
    //   this.checkWxAuth()
    // }
    // 小程序自动登录
    if (this.globalData.uuid && !wx.getStorageSync('refresh_token')) {
      this.toAutoLogin()
    }
  },
      
  /** 发起微信授权检测 如果未授权尝试发起用户信息授权请求 */
  checkWxAuth() {
    // 检查微信是否授权用户信息查询 scope.userInfo
    wx.getSetting({
      success: (res) => {
        console.log("授权", res);
        if (!res.authSetting['scope.userInfo']) {
          this.globalData.hasAuth = false
        } else {
          this.globalData.hasAuth = true
        }
      }
    })
  },
  async toAutoLogin() {
    // 检测是否登录 如果已经登录 或者登录结果为账户未发现 则不再进行自动登录
    if (wx.getStorageSync('refresh_token') || wx.getStorageSync('login_result') === 'account_not_found') return
    let final = {}
    const {
      code
    } = await wx.pro.login({
      timeout: 8000
    })


    const uuid = wx.getStorageSync('uuid')
    console.log('code,uuid', code, uuid);
    try {
      let result = await API_Connect.loginByAuto({
        code,
        uuid
      })
      //console.log('result', result);

      // 如果已经进行过用户授权但是没有获取到unionID
      if (result.reson === 'unionid_not_found') {
        console.log('unionid_not_found');
        const {
          encryptedData,
          iv
        } = await wx.pro.getUserInfo({
          withCredentials: true,
          lang: 'zh_CN'
        })
        console.log('encryptedData', encryptedData, iv);
        final = await API_Connect.accessUnionID({
          code,
          uuid,
          encrypted_data: encryptedData,
          iv
        })
        console.log('final', final);
        if (final.reson && final.reson === "account_not_found") {
          // wx.navigateTo({ url: '/pages/auth/login/login' })
        }
      }
      wx.setStorageSync('login_result', result.reson)
      const {
        access_token,
        refresh_token,
        uid
      } = result.access_token ? result : final
      console.log("登录成功", access_token,
        refresh_token,
        uid);

      // 如果登录成功 存储token(access_token refresh_token) uid 获取用户数据 获取购物车数据
      if (access_token && refresh_token && uid) {
        this.globalData.hasAuth = true
        wx.setStorageSync('access_token', access_token)
        wx.setStorageSync('refresh_token', refresh_token)
        wx.setStorageSync('uid', uid)
        // 获取用户信息 获取购物车信息
        const user = await API_Member.getUserInfo()
        wx.setStorageSync('user', user)
        // 获取购物车信息
        const {
          cart_list
        } = await API_Trade.getCarts();
        wx.setStorageSync('shoplist', cart_list)
        //刷新当前页面的数据
        if (getCurrentPages().length != 0) {
          getCurrentPages()[getCurrentPages().length - 1].onLoad()
          getCurrentPages()[getCurrentPages().length - 1].onShow()
        }
      }
    } catch (e) {
      console.log("错误信息", e)
      wx.setStorageSync('login_result', false)
      // if (e.response.data.code === 'E133') {
      //   wx.navigateTo({ url: '/pages/home/home' })
      //   // 授权信息失效 进行强制授权
      //   this.globalData.hasAuth = false
      // }
    }
  },
  globalData: {
    // uuid
    uuid: '',
    // 是否已授权
    hasAuth: false,
    // 站点信息
    site_name: {},
    // 站点名称
    projectName: '欧品国际商城',
    //苹果手机底部适配
    isIphone: wx.getSystemInfoSync().model.indexOf("iPhone X", "iPhone XS", "iPhone XR", "iPhone XS Max", "iPhone 11", "iPhone 11 pro")
  },
  setComputed(page) {
    let data = page.data
    let dataKeys = Object.keys(data)
    dataKeys.forEach(dataKey => {
      this.observeComputed(page, page.data, dataKey, page.data[dataKey])
    })
  },
  observeComputed(data, key, val, fn) {
    var dataVal = data[key];
    if (dataVal != null && typeof dataVal === 'object') {
      Object.keys(dataVal).forEach(childKey => { // 遍历val对象下的每一个key
        this.observeComputed(page, dataVal, childKey, dataVal[childKey])
      })
    }
    var that = this;
    Object.defineProperty(data, key, {
      configurable: true,
      enumerable: true,
      get: function () {
        return val
      },
      set: function (newVal) {
        val = newVal
        let computed = page.computed //computed对象，每个值都是函数 
        let keys = Object.keys(computed)
        let firstComputedObj = keys.reduce((prev, next) => {
          page.data.$target = function () {
            page.setData({
              [next]: computed[next].call(page)
            })
          }
          prev[next] = computed[next].call(page)
          page.data.$target = null
          return prev
        }, {})
        page.setData(firstComputedObj)
      }
    })
  }
})